package com.qunar.qcf.proxy;

import java.io.IOException;
import java.net.InetSocketAddress;

import com.qunar.qcf.core.RuntimeIoException;
import com.qunar.qcf.core.session.IdleStatus;
import com.qunar.qcf.core.session.IoSessionConfig;
import com.qunar.qcf.filter.codec.ProtocolCodecFilter;
import com.qunar.qcf.filter.codec.serialization.ObjectSerializationCodecFactory;
import com.qunar.qcf.handler.AbstractServerHandler;
import com.qunar.qcf.handler.IoServerHandler;
import com.qunar.qcf.socket.nio.NioSocketAcceptor;
import com.qunar.qcf.util.Constants;

/**
 * qcf server
 * 
 * @author zhangwan
 * @email wan.zhang@qunar.com
 * 
 * @param <T>
 */
public class QCFServer<T> {
	private AbstractServerHandler handler;
	
//	private static final QCFServer instance = new QCFServer(IoServerHandler.class);
	
	public static QCFServer createProxy() {
		return new QCFServer(IoServerHandler.class);
	}
	
	private QCFServer(Class<T> clazz) {
		try {
			handler = (AbstractServerHandler) clazz.newInstance();
		} catch (Exception e) {
			throw new InstantiationError(e.toString());
		}
	}

	public void accept(int port) {
		NioSocketAcceptor acceptor = new NioSocketAcceptor();
		acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
		
		IoSessionConfig cfg = acceptor.getSessionConfig();
		cfg.setReadBufferSize(Constants.READ_BUFFER_SIZE);
		cfg.setIdleTime(IdleStatus.BOTH_IDLE, Constants.BOTH_IDLE);

		try {
			acceptor.setHandler(handler);
			acceptor.bind(new InetSocketAddress(port));
			System.out.println("Listener on server port:" + port);
		} catch (IOException e) {
			throw new RuntimeIoException("bind address failed.");
		}
	}

}
